using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using Stunt.Nutss;
using Stunt.Nutss.Stunt;

namespace EchoClient
{
	class Program
	{
        private static Semaphore semaphore;
        private static Socket socket;
        private static NutssUri uri;

        class Handler : Stunt.Nutss.Stunt.STUNTEventAdapter {
            
            public void connectTCPHandler(Socket sock)
            {
                socket = sock;
                semaphore.Release();
            }
            public void errorHandler(Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }

		static void Main(string[] args)
		{
            try
            {
                uri = new NutssUri(args[0].Equals("-d") ? args[1] : args[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine("Usage: EchoClient [-d] you@your.domain.com");
            }
            try
            {
                if (args[0].Equals("-d"))
                {
                    //log
                }
                STUNTEndpoint sock = new STUNTEndpoint();
                sock.ConnectTCP(uri, new Handler());
                semaphore.WaitOne();
                while (true)
                {
                    byte[] buffer = new byte[255];
                    socket.Receive(buffer);
                    if (buffer == null) break;
                    Console.WriteLine(buffer.ToString());

                    String input = Console.In.ReadLine();
                    buffer = Encoding.UTF8.GetBytes(input);
                    if (buffer == null) break;
                    socket.Send(buffer);
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
			
		}
	}
}
